//MountManager - the program for easy mounting of storage devices in Linux
//Copyright (C) 2007-2008 Tikhonov Sergey
//
//This file is part of MountManager Core
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#include <QDebug>
#include "diskdevice.h"
#include "diskbackup.h"
#include "diskcore.h"

DiskCore::DiskCore(const QString &backupPath,bool debug) : DiskHal(debug), DiskBackUp(backupPath) {
	process = new QProcess;
	connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(processFinished(int,QProcess::ExitStatus)));
}

DiskCore::~DiskCore() {
	delete process;
}

void DiskCore::mount(const QString &blockName,const QString& mountPoint, const QString& fs, const QString& options) {
	process->execute(QString("mount -t %1 -o %2 %3 %4").arg(fs).arg(options).arg(blockName).arg(mountPoint));
}

void DiskCore::unmount(DiskDevice *deviceToUnmount) {
	unmount(deviceToUnmount->blockName());
}

void DiskCore::unmount(const QString &blockName) {
	process->execute(QString("umount %1").arg(blockName));
}

void DiskCore::mountAll() {
	process->execute("mount -a");
}

void DiskCore::unmountAll() {
	process->execute("umount -a");
}

void DiskCore::processFinished(int exitCode, QProcess::ExitStatus /*exitStatus*/) {
	if (exitCode != 0) {
		errorText = QString::fromUtf8(process->readAllStandardError().data());
		qDebug() << "[E] Error appeared:" << errorText;
		if (errorText.isEmpty())
			emit (errorAppeared(tr("There is an unknown error - maybe you haven't enough rights for this action")));
		else
			emit (errorAppeared(tr("Error") + ": " + errorText));
	} else
		errorText.clear();
}

const QString& DiskCore::error() const {
	return errorText;
}
